<template>
  <div class="home-container">
    <!-- 顶部栏 -->
    <div class="header-bar-flex">
      <div class="header-title-left">社团管理系统</div>
      <div class="header-right">
        <div class="user-info-container">
          <div class="notification-icon" @click="showSystemAnnouncements" style="cursor: pointer;">
            <el-badge :value="unreadCount" :hidden="unreadCount === 0">
              <el-icon class="message-icon" style="font-size: 20px;"><Bell /></el-icon>
            </el-badge>
          </div>
          <div class="user-badge">
            <div class="header-user">
              <el-dropdown @command="handleCommand">
                <span class="user-info">
                  <el-avatar :size="32" :src="userInfo.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec643699c2642b92c6726f1epng.png'"></el-avatar>
                  <span class="username">{{ userInfo.username }}</span>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                    <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="home-main-wrapper">
      <!-- 公告轮播滚动屏 -->
      <div class="carousel-announcement-wrapper">
        <el-carousel :interval="5000" arrow="never" indicator-position="outside" height="220px">
          <el-carousel-item v-for="(item, idx) in carouselAnnouncements" :key="idx" @click="showSystemAnnouncements">
            <div class="carousel-card">
              <div class="carousel-title">{{ item.title }}</div>
              <div class="carousel-content">{{ item.content }}</div>
              <div class="carousel-date">{{ item.date }}</div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
      <!-- 消息通知 -->
      <el-card class="section-card notice-card">
        <div class="section-title">消息通知</div>
        <div class="notification-list">
          <el-empty v-if="!messages.length" description="暂无通知" />
          <el-timeline v-else>
            <el-timeline-item
              v-for="message in messages"
              :key="message.id || message.timestamp"
              :timestamp="message.sendTime ? new Date(message.sendTime).toLocaleString() : ''"
              :type="getAnnouncementType({ type: message.type })"
              :class="{ 'new-message-highlight': message.isNew }"
            >
              {{ message.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card>

      <!-- 三栏功能区 -->
      <div class="feature-row">
        <el-card class="section-card feature-card">
          <div class="section-title">社团管理</div>
          <div class="button-group-center">
            <el-button type="primary" @click="goTo('/clubs')">浏览社团</el-button>
            <el-button type="success" @click="goTo('/my-clubs')">我加入的社团</el-button>
          </div>
        </el-card>
        <el-card class="section-card feature-card">
          <div class="section-title">活动管理</div>
          <div class="button-group-center">
            <el-button type="primary" @click="goTo('/activities')">活动列表</el-button>
            <el-button type="success" @click="goTo('/my-activities')">我报名的活动</el-button>
          </div>
        </el-card>
        <el-card class="section-card feature-card">
          <div class="section-title">公告中心</div>
          <div class="button-group-center">
            <el-button type="primary" @click="showSystemAnnouncements">系统公告</el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 添加系统公告抽屉组件 -->
    <el-drawer
      v-model="systemAnnouncementsDrawer"
      title="系统公告"
      direction="rtl"
      size="50%"
      class="system-announcements-drawer"
    >
      <div class="announcements-container">
        <!-- 搜索和筛选区域 -->
        <div class="search-filter-area">
          <el-input
            v-model="searchKeyword"
            placeholder="输入关键字搜索"
            clearable
            @clear="handleSearchAnnouncements"
            @keyup.enter="handleSearchAnnouncements"
            class="search-input"
          ></el-input>
          <el-radio-group v-model="selectedLevel" @change="handleSearchAnnouncements" class="level-select">
            <el-radio-button label="系统级"></el-radio-button>
            <el-radio-button label="社团级"></el-radio-button>
          </el-radio-group>
          <el-button type="primary" :icon="ElIconSearch" @click="handleSearchAnnouncements">搜索</el-button>
        </div>
        
        <!-- 公告列表 -->
        <el-timeline>
          <el-timeline-item
            v-for="announcement in allSystemAnnouncements"
            :key="announcement.id"
            :timestamp="formatAnnouncementTime(announcement)"
            placement="top"
            :type="getAnnouncementType(announcement)"
            :hollow="true"
            :size="'large'"
          >
            <el-card class="announcement-card" :body-style="{ padding: '20px' }">
              <div class="announcement-header">
                <h3>{{ announcement.title }}</h3>
                <div class="announcement-tags">
                  <el-tag size="small" :type="getAnnouncementType(announcement)">
                    {{ getAnnouncementTypeText(announcement) }}
                  </el-tag>
                  <el-tag size="small" type="info" effect="plain">
                    {{ announcement.level }}
                  </el-tag>
                  <el-tag size="small" :type="announcement.readStatus === 1 ? 'success' : 'info'">
                    {{ announcement.readStatus === 1 ? '已读' : '未读' }}
                  </el-tag>
                </div>
              </div>
              <div class="announcement-content">
                <p>{{ announcement.content }}</p>
              </div>
              <div class="announcement-footer" v-if="announcement.readStatus === 0">
                <el-button type="primary" size="small" @click="markAnnouncementAsRead(announcement.id)">
                  标记为已读
                </el-button>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        
        <!-- 无公告提示 -->
        <el-empty v-if="!allSystemAnnouncements.length" description="暂无公告" />
      </div>
    </el-drawer>

    <!-- 个人信息编辑对话框 -->
    <el-dialog v-model="personalInfoDialogVisible" title="编辑个人信息" width="50%">
      <el-form :model="personalInfoForm" label-width="100px" ref="personalInfoFormRef">
        <el-form-item label="用户名">
          <el-input v-model="personalInfoForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="personalInfoForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="personalInfoForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="personalInfoForm.email"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="personalInfoForm.idCard"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="avatarFile">
          <div style="display: flex; flex-direction: column; align-items: flex-start;">
            <el-avatar :size="80" :src="personalInfoAvatarPreviewUrl" style="margin-bottom: 10px;"></el-avatar>
            <el-upload class="upload-demo" action="#" :auto-upload="false" :on-change="handlePersonalInfoAvatarUpload" :limit="1" accept="image/*" :show-file-list="false">
              <template #trigger>
                <el-button type="primary">选择新头像</el-button>
              </template>
            </el-upload>
            <div class="el-upload__tip">请上传图片文件，且不超过 5MB</div>
          </div>
        </el-form-item>
        <!-- 以下字段仅用于展示，不提供编辑 -->
        <el-form-item label="用户ID">
          <span class="form-item-static-text">{{ personalInfoForm.userId }}</span>
        </el-form-item>
        <el-form-item label="创建时间">
          <span class="form-item-static-text">{{ formatAnnouncementTime(personalInfoForm) }}</span>
        </el-form-item>
         <el-form-item label="最后登录">
          <span class="form-item-static-text">{{ formatAnnouncementTime({ createdAt: personalInfoForm.lastLogin }) }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <span class="form-item-static-text">{{ personalInfoForm.role || '普通用户' }}</span>
        </el-form-item>
        <el-form-item label="状态">
          <span class="form-item-static-text">{{ personalInfoForm.status === 1 ? '启用' : '禁用' }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="personalInfoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPersonalInfoForm">保存</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { userApi } from '../api'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { HomeFilled, User, List, Calendar, Bell, Search as ElIconSearch } from '@element-plus/icons-vue'
import api from '../api'
import { Client } from '@stomp/stompjs'
import SockJS from 'sockjs-client'

const router = useRouter()
const userInfo = ref({
  username: '',
  avatarUrl: '',
  role: ''
})

// 添加轮播公告、未读和已读公告的响应式变量
const carouselAnnouncements = ref([])
const unreadAnnouncements = ref([])
const readAnnouncements = ref([])

// WebSocket相关状态
const stompClient = ref(null)
const connected = ref(false)
const messages = ref([])
const shownAnnouncementIds = ref(new Set())

// 新增的响应式数据
const notifications = ref([])
const unreadCount = ref(0)

// 公告搜索和筛选相关的响应式数据
const searchKeyword = ref('') // 关键字，默认为空
const selectedLevel = ref('系统级') // 公告级别，默认为系统级

// 新增：个人信息编辑相关状态和方法
const personalInfoDialogVisible = ref(false);
const personalInfoFormRef = ref(null);
const personalInfoForm = ref({
  userId: null,
  username: '',
  realName: '',
  phone: '',
  email: '',
  idCard: '',
  avatarFile: null, // 用于存储新的头像文件
  createdAt: '',
  lastLogin: '',
  role: '',
  status: null
});
const personalInfoAvatarPreviewUrl = ref('');
const originalPersonalInfo = ref({
    realName: '',
    phone: '',
    email: '',
    idCard: '',
    avatarUrl: ''
});

// 初始化通知的方法
const initNotifications = async () => {
  try {
    // 这里应该调用后端API获取通知数据（如果通知不仅仅是系统公告）
    // 当前是模拟数据，可以根据实际情况修改或移除
    notifications.value = [
      {
        id: 1,
        type: 'success',
        content: '您的社团申请已通过审核',
        time: '2024-01-20 10:00:00'
      },
      {
        id: 2,
        type: 'info',
        content: '新的系统公告已发布',
        time: '2024-01-19 15:30:00'
      }
    ]
    // unreadCount 的更新将由 loadUnreadCount 负责
  } catch (error) {
    console.error('获取通知失败:', error)
    ElMessage.error('获取通知失败')
  }
}

// 新增函数：加载未读数量
const loadUnreadCount = async () => {
  try {
    const userId = userInfo.value.id;
    if (!userId) {
      console.error('无法获取用户ID，无法加载未读数量');
      return;
    }
    const response = await api.get('/userclubs/selectUnreadCount', {
      params: {
        userId: userId
      }
    });
    if (response.code === 200 && response.data !== undefined) {
      unreadCount.value = response.data;
    } else {
      console.error('获取未读数量失败:', response.message);
      // 失败时可以将未读数量设置为0或者保持原值
      // unreadCount.value = 0;
    }
  } catch (error) {
    console.error('获取未读数量失败:', error);
    ElMessage.error('获取未读数量失败');
    // unreadCount.value = 0;
  }
}

// 添加新的响应式数据
const systemAnnouncementsDrawer = ref(false)
const allSystemAnnouncements = ref([])

// 修改 loadSystemAnnouncements 函数
const loadSystemAnnouncements = async () => {
  console.log('loadSystemAnnouncements function called');
  try {
    // 获取当前用户ID
    const userId = userInfo.value.id;
    if (!userId) {
      console.error('无法获取用户ID，无法加载系统公告');
      return;
    }

    // 构建 AnnouncementQueryDTO 对象
    const announcementQueryDTO = {
      keyword: searchKeyword.value || null, // 关键字，为空字符串时传递 null
      level: selectedLevel.value, // 公告级别
      userId: userId // 用户ID
    };

    // 调用后端接口，改为POST请求，传递 DTO 对象作为请求体
    const response = await api.post('/userclubs/selectSystemAnnouncements', announcementQueryDTO);

    if (response.code === 200) {
      // 保存所有公告数据
      allSystemAnnouncements.value = response.data;

      // 分离已读和未读公告
      unreadAnnouncements.value = response.data.filter(a => a.readStatus === 0);
      readAnnouncements.value = response.data.filter(a => a.readStatus === 1);

      // 对轮播图公告按时间排序并只取最近的三条
      const sortedAnnouncements = response.data
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
        .slice(0, 3)
        .map(ann => ({
          title: ann.title,
          content: ann.content,
          date: ann.createdAt ? new Date(ann.createdAt).toLocaleDateString() : ''
        }));
      
      carouselAnnouncements.value = sortedAnnouncements;
    } else {
      console.error('获取系统公告失败:', response.message);
      ElMessage.error('获取系统公告失败');
      carouselAnnouncements.value = [];
      allSystemAnnouncements.value = [];
    }
  } catch (error) {
    console.error('获取系统公告失败:', error);
    ElMessage.error('获取系统公告失败');
    carouselAnnouncements.value = [];
    allSystemAnnouncements.value = [];
  }
}

// 添加显示系统公告的方法
const showSystemAnnouncements = async () => {
  systemAnnouncementsDrawer.value = true;
  // 可以在打开抽屉时加载默认的系统公告
  // await loadSystemAnnouncements(); 
}

// 添加搜索按钮的点击事件处理函数
const handleSearchAnnouncements = () => {
  loadSystemAnnouncements(); // 调用加载函数，会使用当前的 searchKeyword 和 selectedLevel
}

// 格式化公告时间
const formatAnnouncementTime = (announcement) => {
  const createdStr = announcement.createdAt
  const updatedStr = announcement.updatedAt

  let created = null
  let updated = null

  // 直接解析标准的 ISO 8601 格式
  if (createdStr) {
    created = new Date(createdStr)
  }

  if (updatedStr) {
    updated = new Date(updatedStr)
  }

  let timeStr = created && !isNaN(created.getTime()) ? `创建时间：${created.toLocaleString()}` : '创建时间：无效日期'

  // 如果更新时间与创建时间不同且有效，则显示更新时间
  if (updated && !isNaN(updated.getTime()) && updated.getTime() !== (created ? created.getTime() : NaN)) {
    timeStr += `\n更新时间：${updated.toLocaleString()}`
  }

  return timeStr
}

// 获取公告类型对应的样式
const getAnnouncementType = (item) => {
  const typeMap = {
    'NOTICE': 'info',
    'EVENT': 'success',
    'SYSTEM': 'warning'
  }
  // 检查 item.type 是否在 typeMap 中，否则返回默认值
  return typeMap[item.type] || 'primary'
}

// 获取公告类型文本
const getAnnouncementTypeText = (announcement) => {
  const typeMap = {
    'NOTICE': '通知',
    'EVENT': '活动',
    'SYSTEM': '系统'
  }
  return typeMap[announcement.type] || '公告'
}

// 初始化WebSocket连接
const initWebSocket = () => {
  const userId = JSON.parse(localStorage.getItem('userInfo'))?.id
  if (!userId) {
    console.error('无法获取用户ID，WebSocket连接失败')
    return
  }

  const socket = new SockJS('http://localhost:8080/LZ/ws')
  stompClient.value = new Client({
    webSocketFactory: () => socket,
    debug: (str) => {
      console.log('STOMP: ' + str)
    },
    reconnectDelay: 5000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000,
    connectHeaders: {
      'user': userId.toString()
    }
  })

  stompClient.value.onConnect = () => {
    console.log('已连接到WebSocket服务器')
    console.log('当前用户ID:', userId)
    connected.value = true

    // 订阅广播消息
    stompClient.value.subscribe('/topic/broadcast', onMessageReceived)

    // 订阅私聊消息
    stompClient.value.subscribe('/user/queue/private', onMessageReceived)

     // 订阅群发消息
    // stompClient.value.subscribe('/topic/group/*', onMessageReceived)
  }

  stompClient.value.onStompError = (frame) => {
    console.error('STOMP错误:', frame)
    connected.value = false
  }

  stompClient.value.onWebSocketError = (event) => {
    console.error('WebSocket错误:', event)
    connected.value = false
  }

  stompClient.value.onWebSocketClose = (event) => {
    console.log('WebSocket连接关闭:', event)
    connected.value = false
  }

  stompClient.value.activate()
}

// 处理接收到的消息
const onMessageReceived = (payload) => {
  const message = JSON.parse(payload.body)
  console.log('收到消息:', message)

  // 检查消息是否为公告类型（根据后端的type字段判断）
  if (['NOTICE', 'EVENT', 'SYSTEM'].includes(message.type)) {
    showAnnouncement(message) // 显示通知
    // 收到新公告后刷新公告列表和未读数量 (Moved outside the if block)
    // loadSystemAnnouncements()
    // loadUnreadCount()
  }

  // Load and refresh announcements and unread count for any new message
  loadSystemAnnouncements();
  loadUnreadCount();

  // Add a timestamp to the message for persistence and highlighting logic
  const messageWithTimestamp = { ...message, receivedAt: Date.now() };

  // 添加新消息标记并添加到列表头部 (仅用于当前会话的短暂高亮)
  const newMessageForDisplay = { ...messageWithTimestamp, isNew: true };
  messages.value.unshift(newMessageForDisplay);

  // Save the message to localStorage
  try {
    const storedMessages = JSON.parse(localStorage.getItem('userMessages') || '[]');
    storedMessages.unshift(messageWithTimestamp);
    // Keep only the last 50 messages to avoid excessive localStorage usage
    localStorage.setItem('userMessages', JSON.stringify(storedMessages.slice(0, 50)));
  } catch (e) {
    console.error('Error saving message to localStorage:', e);
  }

  // Optional: Remove highlight after a few seconds (only for current session display)
  setTimeout(() => {
    // Find the message in the current messages list by ID or content/timestamp combination
     const msgIndex = messages.value.findIndex(m => 
       (m.id && m.id === newMessageForDisplay.id) || 
       (m.content === newMessageForDisplay.content && m.receivedAt === newMessageForDisplay.receivedAt) // Use receivedAt for better uniqueness
     );
     if(msgIndex !== -1) messages.value[msgIndex].isNew = false;
  }, 5000); // Highlight for 5 seconds
}

// 展示公告消息并去重
const showAnnouncement = (announcement) => {
  if (!announcement.id) return
  if (shownAnnouncementIds.value.has(announcement.id)) return
  shownAnnouncementIds.value.add(announcement.id)

  // 使用 ElNotification 替代 ElMessage，样式更醒目
  ElNotification({
    title: `新公告: ${announcement.title}`,
    message: announcement.content.substring(0, 100) + (announcement.content.length > 100 ? '...' : ''), // 显示部分内容
    type: getNotificationType(announcement.type), // 根据公告类型设置通知类型
    duration: 8000, // 通知显示时长
    position: 'top-right' // 通知位置
  })
}

// 根据公告类型获取通知类型
const getNotificationType = (announcementType) => {
  const typeMap = {
    'NOTICE': 'info',
    'EVENT': 'success',
    'SYSTEM': 'warning'
  }
  return typeMap[announcementType] || 'info' // 默认为 info 类型
}

// 断开WebSocket连接
const disconnectWebSocket = () => {
  if (stompClient.value) {
    stompClient.value.deactivate()
    connected.value = false
  }
}

// 合并后的onMounted钩子
onMounted(() => {
  console.log('Home.vue onMounted hook triggered')

  // Load messages from localStorage first
  try {
    const storedMessages = JSON.parse(localStorage.getItem('userMessages') || '[]');
    const now = Date.now();
    // Filter out old messages (e.g., older than 10 minutes) and add isNew flag based on recency
    messages.value = storedMessages.filter(msg => {
      const isRecent = (now - msg.receivedAt) < 10 * 60 * 1000; // Messages received within the last 10 minutes are considered 'new'
      if (isRecent) {
        msg.isNew = true; // Mark as new for highlighting
        // Set a timeout to remove the highlight later (relative to now, not receivedAt)
        setTimeout(() => {
          // Find the message in the current messages list by ID or content/timestamp combination
           const msgIndex = messages.value.findIndex(m => 
             (m.id && m.id === msg.id) || 
             (m.content === msg.content && m.receivedAt === msg.receivedAt) // Use receivedAt for better uniqueness
           );
           if(msgIndex !== -1) messages.value[msgIndex].isNew = false;
        }, 5000); // Highlight for 5 seconds
      }
      return isRecent || (now - msg.receivedAt) < 24 * 60 * 60 * 1000; // Keep messages from the last 24 hours
    });
     // Sort messages by received time, newest first
    messages.value.sort((a, b) => b.receivedAt - a.receivedAt);

  } catch (e) {
    console.error('Error loading messages from localStorage:', e);
    messages.value = []; // Clear messages if loading fails
  }

  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    try {
      userInfo.value = JSON.parse(storedUserInfo)
      // 如果没有用户信息，跳转到登录页
      if (!userInfo.value.username) {
        router.push('/login')
      } else {
        // 用户信息解析成功后，初始化通知并加载公告
        initNotifications() // 加载通知（如果不是仅指系统公告）
        console.log('initNotifications finished')
        loadSystemAnnouncements() // 加载系统公告列表
        loadUnreadCount(); // 加载未读数量并更新通知图标
        initWebSocket() // 初始化WebSocket连接
      }
    } catch (error) {
      console.error('解析用户信息失败:', error)
      ElMessage.error('用户信息解析失败，请重新登录')
      router.push('/login')
    }
  } else {
    // 没有用户信息，直接跳转登录页
    router.push('/login')
  }
})

// 在组件卸载前断开WebSocket连接
onBeforeUnmount(() => {
  disconnectWebSocket()
})

// 处理下拉菜单命令
const handleCommand = async (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await userApi.logout()
        localStorage.clear()
        router.push('/login')
        ElMessage.success('退出登录成功')
      } catch (error) {
        ElMessage.error('退出登录失败：' + error.message)
      }
    })
  } else if (command === 'profile') {
    // 打开个人信息编辑对话框
    const storedUserInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    if (storedUserInfo) {
      // 填充个人信息编辑表单
      personalInfoForm.value = {
        userId: storedUserInfo.id,
        username: storedUserInfo.username,
        realName: storedUserInfo.real_name || '',
        phone: storedUserInfo.phone || '',
        email: storedUserInfo.email || '',
        idCard: storedUserInfo.id_card || '',
        avatarFile: null, // 编辑时默认为空
        createdAt: storedUserInfo.createdAt || '',
        lastLogin: storedUserInfo.lastLogin || '',
        role: storedUserInfo.role || '',
        status: storedUserInfo.status
      };
      // 保存原始信息用于比较
      originalPersonalInfo.value = {
        realName: storedUserInfo.real_name || '',
        phone: storedUserInfo.phone || '',
        email: storedUserInfo.email || '',
        idCard: storedUserInfo.id_card || '',
        avatarUrl: storedUserInfo.avatarUrl || ''
      };
      // 设置头像预览
      personalInfoAvatarPreviewUrl.value = storedUserInfo.avatarUrl || '';
      // 打开编辑对话框
      personalInfoDialogVisible.value = true;
    } else {
      ElMessage.error('无法获取个人信息，请重新登录。');
      router.push('/login');
    }
  }
}

// 导航跳转函数
const goTo = (path) => {
  router.push(path);
}

// 标记公告为已读
const markAnnouncementAsRead = async (announcementId) => {
  try {
    // 调用新的后端接口，传递 announcementId 作为 announcement_id 参数
    const response = await api.post('/userclubs/updateAnnouncementReadStatus', null, { // POST请求但没有请求体，参数在params中
      params: {
        announcement_id: announcementId // 修改参数名为 announcement_id
      }
    });

    if (response.code === 200) {
      ElMessage.success('标记已读成功');
      // 更新本地状态，将该公告的 readStatus 设置为 1
      const announcement = allSystemAnnouncements.value.find(a => a.id === announcementId);
      if (announcement) {
        announcement.readStatus = 1;
        // 从未读列表中移除，添加到已读列表
        unreadAnnouncements.value = unreadAnnouncements.value.filter(a => a.id !== announcementId);
        readAnnouncements.value.push(announcement);
        // 更新未读数量
        unreadCount.value = unreadAnnouncements.value.length;

        // 重新加载公告列表以确保状态同步（可选，如果后端推送状态更新则不需要）
        // loadSystemAnnouncements();
      }
    } else {
      console.error('标记公告已读失败:', response.message);
      ElMessage.error('标记公告已读失败：' + response.message);
    }
  } catch (error) {
    console.error('标记公告已读失败:', error);
    ElMessage.error('标记公告已读失败');
  }
}

// 新增：处理个人信息头像上传
const handlePersonalInfoAvatarUpload = (file) => {
  if (file) {
    const isImage = file.raw.type.startsWith('image/');
    const isLt5M = file.raw.size / 1024 / 1024 < 5;
    if (!isImage) {
      ElMessage.error('只能上传图片文件！');
      personalInfoForm.value.avatarFile = null;
      personalInfoAvatarPreviewUrl.value = originalPersonalInfo.value.avatarUrl;
      return false;
    }
    if (!isLt5M) {
      ElMessage.error('图片大小不能超过 5MB！');
      personalInfoForm.value.avatarFile = null;
      personalInfoAvatarPreviewUrl.value = originalPersonalInfo.value.avatarUrl;
      return false;
    }
    personalInfoForm.value.avatarFile = file.raw;
    personalInfoAvatarPreviewUrl.value = URL.createObjectURL(file.raw);
    return true;
  }
  personalInfoForm.value.avatarFile = null;
  personalInfoAvatarPreviewUrl.value = originalPersonalInfo.value.avatarUrl;
  return false;
};

// 新增：提交个人信息表单
const submitPersonalInfoForm = async () => {
  try {
    // 可以在这里添加表单验证逻辑，使用 personalInfoFormRef
    // 例如：personalInfoFormRef.value.validate(async (valid) => { if (!valid) return; ... });

    const formData = new FormData();

    // 构建更新请求对象，只包含被修改的字段
    const updatePayload = {
      userId: personalInfoForm.value.userId,
      // 检查字段是否修改，只发送修改过的字段
      realName: personalInfoForm.value.realName !== originalPersonalInfo.value.realName ? personalInfoForm.value.realName : null,
      phone: personalInfoForm.value.phone !== originalPersonalInfo.value.phone ? personalInfoForm.value.phone : null,
      email: personalInfoForm.value.email !== originalPersonalInfo.value.email ? personalInfoForm.value.email : null,
      idCard: personalInfoForm.value.idCard !== originalPersonalInfo.value.idCard ? personalInfoForm.value.idCard : null,
      originalAvatarUrl: originalPersonalInfo.value.avatarUrl // 发送原始头像URL以便后端判断是否需要删除旧头像
    };

    // 添加文件（如果有新头像文件）
    if (personalInfoForm.value.avatarFile) {
      formData.append('file', personalInfoForm.value.avatarFile);
    } else {
       // 如果没有新头像文件，但原始头像URL存在，发送一个空文件表示不更新头像
       // 如果原始头像URL也不存在，则不发送文件字段
       if(originalPersonalInfo.value.avatarUrl) {
          const emptyBlob = new Blob([''], { type: 'application/octet-stream' });
          formData.append('file', emptyBlob, ''); // 空文件名表示不上传新文件
       }
    }

    // 添加更新请求对象为 JSON 字符串
    formData.append('updatePersonalInfoRequestDto', new Blob([JSON.stringify(updatePayload)], { type: 'application/json' }));

    // 调用后端 API 进行更新
    // 请根据您的后端接口实际情况修改这里的 URL 和请求方法
    const response = await api.post('/userclubs/updatePersonalInfo', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });

    if (response.code === 200) {
      ElMessage.success('个人信息更新成功');
      personalInfoDialogVisible.value = false;

      // 更新本地存储的用户信息
      const updatedUserInfo = JSON.parse(localStorage.getItem('userInfo'));
      if (updatePayload.realName !== null) updatedUserInfo.real_name = updatePayload.realName;
      if (updatePayload.phone !== null) updatedUserInfo.phone = updatePayload.phone;
      if (updatePayload.email !== null) updatedUserInfo.email = updatePayload.email;
      if (updatePayload.idCard !== null) updatedUserInfo.id_card = updatePayload.idCard;
      // 如果后端返回了新的头像URL，更新本地存储和userInfo ref
      if (response.data && response.data.avatarUrl) {
        updatedUserInfo.avatarUrl = response.data.avatarUrl;
      }
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));

      // 更新页面上显示的用户信息（如果需要，例如顶部的头像和姓名）
      userInfo.value = updatedUserInfo; // 这会触发顶部 userInfo 的更新

    } else {
      ElMessage.error(response.message || '更新个人信息失败');
    }
  } catch (error) {
    console.error('更新个人信息失败:', error);
    ElMessage.error('更新个人信息网络错误');
  }
};

</script>

<style scoped>
.home-container {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #f7fafc 0%, #e3f6f5 100%);
}

.header-bar-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
  padding: 0 40px;
  background: #f7fafc;
  border-bottom: 1.5px solid #e3e8ee;
}

.header-title-left {
  font-size: 26px;
  font-weight: bold;
  color: #3a5a40;
  letter-spacing: 2px;
}

.user-badge {
  background: rgba(245, 245, 220, 0.7);
  border-radius: 20px;
  padding: 5px 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  font-size: 14px;
  color: #333;
}

.home-main-wrapper {
  max-width: 1200px;
  margin: 40px auto 0 auto;
  padding: 0 20px 40px 20px;
}

.notice-card {
  margin-bottom: 32px;
}

.section-card {
  border-radius: 16px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  background: #ffffffcc;
  border: 1.5px solid #e3e8ee;
  transition: box-shadow 0.2s;
}

.section-card:hover {
  box-shadow: 0 8px 32px 0 rgba(100, 200, 180, 0.18);
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 18px;
  color: #3a5a40;
  letter-spacing: 1px;
}

.feature-row {
  display: flex;
  gap: 24px;
  justify-content: center;
  flex-wrap: wrap;
}

.feature-card {
  flex: 1 1 320px;
  min-width: 280px;
  max-width: 360px;
  margin-bottom: 0;
}

.button-group-center {
  display: flex;
  justify-content: center;
  gap: 18px;
  margin-bottom: 8px;
}

.el-button--primary {
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%);
  border: none;
  color: #22577a;
}
.el-button--primary:hover {
  background: linear-gradient(90deg, #b8e1dd 0%, #8fd6e1 100%);
  color: #38a3a5;
}
.el-button--success {
  background: linear-gradient(90deg, #b7e4c7 0%, #d8f3dc 100%);
  border: none;
  color: #40916c;
}
.el-button--success:hover {
  background: linear-gradient(90deg, #d8f3dc 0%, #b7e4c7 100%);
  color: #52b788;
}

.notification-list {
  margin-top: 8px;
  max-height: 200px; 
  overflow-y: auto; 
  padding-right: 10px; 
}

/* 优化滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  background: #e3f6f5;
}
::-webkit-scrollbar-thumb {
  background: #b8e1dd;
  border-radius: 4px;
}

.carousel-announcement-wrapper {
  margin-bottom: 32px;
  border-radius: 20px;
  overflow: hidden;
}
.el-carousel {
  border-radius: 20px;
}
.carousel-card {
  width: 100%;
  height: 220px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
  border-radius: 20px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  text-align: center;
  position: relative;
  padding: 20px 60px; /* 增加左右内边距，确保内容不会贴近边缘 */
  overflow: hidden; /* 防止内容溢出容器 */
  box-sizing: border-box; /* 确保内边距不会增加元素总宽度 */
}
.carousel-title {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 18px;
  letter-spacing: 2px;
  text-shadow: 0 2px 8px rgba(0,0,0,0.10);
  width: 100%; /* 确保宽度为100% */
  max-width: 90%; /* 限制最大宽度，防止文字靠近边缘 */
  white-space: normal; /* 允许文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制最多显示2行 */
  -webkit-box-orient: vertical;
  margin-left: auto;
  margin-right: auto;
}
.carousel-content {
  font-size: 1.15rem;
  margin-bottom: 16px;
  text-shadow: 0 1px 4px rgba(0,0,0,0.08);
  width: 100%; /* 确保宽度为100% */
  max-width: 90%; /* 限制最大宽度，防止文字靠近边缘 */
  white-space: normal; /* 允许文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制最多显示3行 */
  -webkit-box-orient: vertical;
  margin-left: auto;
  margin-right: auto;
}
.carousel-date {
  font-size: 1rem;
  opacity: 0.85;
  margin-top: auto; /* 将日期推到底部 */
  width: 100%;
  max-width: 90%;
  margin-left: auto;
  margin-right: auto;
}
.el-carousel__indicators--outside {
  bottom: 18px !important;
}
.el-carousel__indicator button {
  background: #fff !important;
  opacity: 0.5;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin: 0 4px;
  border: none;
  transition: opacity 0.2s;
}
.el-carousel__indicator.is-active button {
  opacity: 1;
  background: #e3f6f5 !important;
}

/* 优化系统公告抽屉样式 */
.system-announcements-drawer :deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  font-size: 18px;
  font-weight: 600;
  color: #3a5a40;
}

.announcements-container {
  padding: 20px;
  height: calc(100vh - 60px); /* Adjust height for search/filter area */
  overflow-y: auto;
  background: #f8f9fa;
}

.search-filter-area {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  flex-grow: 1;
  max-width: 300px; /* Limit search input width */
}

.level-select .el-radio-button__inner {
  padding: 9px 15px;
}

.announcement-tags {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap; /* Add wrap to handle overflow */
}

.announcement-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  margin-right: 10px; /* Add margin to separate title and tags */
}

.announcement-content {
  color: #5c6b73;
  line-height: 1.6;
  font-size: 14px;
}

.announcement-content p {
  margin: 0;
  white-space: pre-wrap;
}

.announcement-footer {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-timeline-item__timestamp) {
  white-space: pre-line;
  font-size: 13px;
  color: #909399;
  padding: 4px 8px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 8px;
}

:deep(.el-timeline-item__node) {
  background-color: #fff;
  border: 2px solid #409eff;
}

:deep(.el-timeline-item__tail) {
  border-left: 2px solid #e4e7ed;
}

:deep(.el-timeline-item__content) {
  margin-left: 16px;
}

/* 自定义滚动条样式 */
.announcements-container::-webkit-scrollbar {
  width: 6px;
}

.announcements-container::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.announcements-container::-webkit-scrollbar-track {
  background: #f5f7fa;
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  font-size: 12px;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info-container {
  display: flex;
  align-items: center;
  gap: 16px;
  height: 100%;
}

.notification-icon {
  display: flex;
  align-items: center;
  height: 100%;
}

.user-badge {
  height: 100%;
  display: flex;
  align-items: center;
}

.header-user {
  height: 100%;
  display: flex;
  align-items: center;
}

/* 消息通知列表的时间线样式 */
.notification-list :deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 13px;
  /* 其他样式根据需要调整 */
}

.notification-list :deep(.el-timeline-item__content) {
  color: #5c6b73;
  font-size: 14px;
  line-height: 1.6;
  /* 其他样式根据需要调整 */
}

/* Add a new style for highlighting new messages */
.new-message-highlight {
  background-color: #fffbe6; /* A slightly more noticeable yellow background */
  border-left: 5px solid #ffcc00; /* Add a yellow left border */
  padding-left: 10px; /* Add some padding to the left due to border */
  transition: background-color 0.5s ease-in-out, border-left-color 0.5s ease-in-out; /* Smooth transition for both */
}

/* 新增/修改样式以匹配 ClubAdmin.vue 的个人信息编辑对话框 */
.form-item-static-text {
  font-size: 14px;
  color: #606266;
}

.el-dialog__header {
  padding: 16px 24px;
  margin-right: 0;
  border-bottom: 1px solid #f0f0f0;
}

.el-dialog__title {
  font-size: 17px;
  font-weight: 500;
}

.el-dialog__body {
  padding: 20px 24px;
}

.el-dialog__footer {
  padding: 12px 24px;
  border-top: 1px solid #f0f0f0;
}
</style>